package com.test.com;

import org.junit.Test;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by user on 17/3/31.
 */
public class scheduleWithFixedDelay {

    @Test
    public void test() throws InterruptedException {
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);

        System.out.println("Current Time = "+new Date());
        for(int i=0; i<1; i++){
            Thread.sleep(1000);
            WorkerThread worker = new WorkerThread("do heavy processing");
            //scheduledThreadPool.schedule(worker, 3, TimeUnit.SECONDS);
            //scheduledThreadPool.scheduleAtFixedRate(worker, 5, 5, TimeUnit.SECONDS);
            scheduledThreadPool.scheduleWithFixedDelay(worker, 5, 3, TimeUnit.SECONDS);
        }
        Thread.sleep(300000);

        scheduledThreadPool.shutdown();
        while(!scheduledThreadPool.isTerminated()){
        }
        System.out.println("Finished all threads");
    }


    public class WorkerThread implements Runnable{

        private String command;

        public WorkerThread(String s){
            this.command=s;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+" Start. Time = "+new Date());
            processCommand();
            System.out.println(Thread.currentThread().getName()+" End. Time = "+new Date());
        }

        private void processCommand() {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        @Override
        public String toString(){
            return this.command;
        }
    }
}
